#include "producttypeeditor.h"
#include "ui_producttypeeditor.h"

#include <QDateTime>
#include "publics.h"
#include <QMessageBox>
ProductTypeEditor::ProductTypeEditor(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::ProductTypeEditor)
{
    ui->setupUi(this);
    pubs = new PublicsWidget(this);
    ui->verticalLayout->addWidget(pubs);
}

ProductTypeEditor::~ProductTypeEditor()
{
    delete ui;
}

void ProductTypeEditor::setMode()
{
    if (theMode == "New")
        {
        this->setWindowTitle("New Product Type");
        pubs->setEnabled(false);
        }
    else if (theMode == "View")
        {
        this->setWindowTitle("View Product Type");
        ui->buttonBox->setEnabled(false);
        ui->lineEditProductType->setReadOnly(true);
        LoadProductCategoryDetails();
        }
    else if (theMode == "Edit")
        {
        this->setWindowTitle("Edit Product Type");
        LoadProductCategoryDetails();
        }
}

void ProductTypeEditor::LoadProductCategoryDetails()
{
    QSqlQuery *qu = new QSqlQuery(tr("SELECT * FROM producttypes WHERE ProductTypeID = '%1'").arg(theID), db);

    while(qu->next())
        {
        ui->lineEditProductType->setText(qu->value(1).toString());

        pubs->db = db;
        pubs->RefNumber = qu->value(2).toString();
        pubs->LoadData();
        }
}

void ProductTypeEditor::changeEvent(QEvent *e)
{
    QDialog::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void ProductTypeEditor::on_buttonBox_accepted()
{
    if (theMode == "New")
        {
        Publics *pubs = new Publics();

        QString RefNo = tr("PRTP-%1").arg(pubs->randomNumber());
        QSqlQuery *qu = new QSqlQuery(tr("INSERT INTO producttypes (`ProductType`, `RefNumber`) VALUES ('%1', '%2')")
                                      .arg(ui->lineEditProductType->text(), RefNo) , db );
        qu = new QSqlQuery(tr("INSERT INTO publics (RefNumber) VALUES ('%1')").arg(RefNo));
        qu->clear();
        }
    else if (theMode == "Edit")
        {

        pubs->SaveData();
        QSqlQuery *qu = new QSqlQuery(tr("UPDATE producttypes SET `ProductType` = '%1' WHERE producttypeid = '%2'")
                                      .arg(ui->lineEditProductType->text(), theID), db );
        qu->clear();
        }
}
